package com.example.questionsystem.modules.qu.controller;

import cn.hutool.core.io.FileUtil;

import cn.hutool.core.io.resource.InputStreamResource;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.questionsystem.core.api.ApiRest;
import com.example.questionsystem.core.api.controller.BaseController;
import com.example.questionsystem.modules.qu.Vo.QuestionCategory;
import com.example.questionsystem.modules.qu.Vo.QuestionVO;
import com.example.questionsystem.modules.qu.dto.QuestionBankDto;
import com.example.questionsystem.modules.qu.dto.QuestionDTO;
import com.example.questionsystem.modules.qu.dto.UpdateQuestionContentRequest;
import com.example.questionsystem.modules.qu.entity.QuestionBanks;
import com.example.questionsystem.modules.qu.service.ProjectsService;
import com.example.questionsystem.modules.qu.service.QuestionBankService;
import com.example.questionsystem.modules.qu.service.SubjectsService;

import com.example.questionsystem.modules.qu.util.*;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.annotation.Resource;
import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
//导入相关包
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;


@Slf4j
@Api(tags = {"录入题目"})
@RestController
@RequestMapping("/question")
public class QuestionController extends BaseController {


    @Resource
    private QuestionBankService questionBanksService;
    @Resource
    private SubjectsService subjectService;
    @Resource
    private ProjectsService projectsService;

    @GetMapping("/download")
    public ResponseEntity<Object> downloadFile() throws IOException {
        ClassPathResource resource = new ClassPathResource("upload/操作说明.docx");

        if (!resource.exists()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(success("文件不存在，请检查资源目录", null));
        }

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"操作说明.docx\"")
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }
    @GetMapping("/getDefaultPath")
    public ApiRest getDefaultDirectory() {
        return success("默认路径获取成功", "C:/kz");
    }


    @PostMapping("/generateHtml")
    public ApiRest generateHtmlFile(@RequestBody Map<String, String> request) {
        try {
            // 获取项目名称和科目名称
            String projectName = projectsService.getById(request.get("projectId")).getProjectName();
            String subjectName = subjectService.getSubjectSessionsById(request.get("subjectId")).getSubjectName();

            // 创建目标目录
            String outputPath = request.get("outputPath");
            Path outputDir = Paths.get(outputPath + "/check/" + request.get("subjectId"));
            Files.createDirectories(outputDir);

            // 解析 HTML 内容
            String content = request.get("content");
            content = HtmlQuestionRenumberUtil.renumberQuestions(content);

            // 生成 HTML 文件
            Path filePath = outputDir.resolve(projectName + "_" + subjectName + ".html");
            Files.write(filePath, content.getBytes(StandardCharsets.UTF_8));
            if (Desktop.isDesktopSupported()) {
                Desktop desktop = Desktop.getDesktop();
                if (desktop.isSupported(Desktop.Action.OPEN)) {
                    desktop.open(filePath.toFile());
                } else if (desktop.isSupported(Desktop.Action.BROWSE)) {
                    desktop.browse(filePath.toUri());
                }
            }

            return success("生成成功，检查 " + outputDir.toString() + " 目录", filePath.toString());
        } catch (Exception e) {
            return failure("生成失败：" + e.getMessage());
        }
    }

    @PostMapping("/search")
    public ApiRest<IPage<QuestionVO>> search(@RequestBody QuestionDTO questionDTO) {
        // 设置分页参数
        if (questionDTO.getPageNum() <= 0) {
          questionDTO.setPageNum(1);
        }

        if (questionDTO.getPageSize() <= 0) {
            questionDTO.setPageSize(10);
        }
        IPage<QuestionVO> search = questionBanksService.search(questionDTO);
        return success("查询成功", search);
    }


    // 删除该项目的科目的所有题目
    @PostMapping("/deleteQuestion")
    public ApiRest deleteQuestion(@RequestBody Map<String, String> request) {
        // 获取科目名称
       String subjectId = request.get("subjectId");
        // 删除该科目的所有题目
        questionBanksService.deleteBySubjectQuestion(subjectId);
        return success("删除成功");
    }


    @PostMapping("/save")
    public ApiRest save(@RequestBody QuestionBankDto questionBankDto ) {
        questionBanksService.batchSave(questionBankDto);
        return success("保存成功");
    }

    /**
     * 更新题目内容（题干HTML与纯文本）
     */
    @PostMapping("/updateContent")
    public ApiRest updateContent(@RequestBody UpdateQuestionContentRequest req) {
        if (req == null || req.getQuestionId() == null || req.getQuestionId().trim().isEmpty()) {
            return failure("题目ID不能为空", null);
        }
        try {
            questionBanksService.updateQuestionContent(req.getQuestionId(), req.getQuestionHtml());
            return success("更新成功", null);
        } catch (Exception e) {
            return failure("更新失败: " + e.getMessage(), null);
        }
    }
    @PostMapping(value = "/recognition")
    public ApiRest recognitionQu(@RequestBody Map<String,String> request) throws IOException {
        String content = request.get("content");
        Document doc = HtmlParserUtils.parseHtml(content);
        // 在解析前进行模板规则校验，不符合规则直接抛业务异常，由全局异常处理返回给前端
        HtmlParserUtils.validateTemplateOrThrow(doc);
        // 提取判断题
        List<String> judgmentQuestions = HtmlParserUtils.extractJudgmentQuestions(doc);
        HashMap<String,  List<String>> judgmentQuestionsHashMap = new HashMap<>();
        judgmentQuestionsHashMap.put("判断题", judgmentQuestions);
        // 提取单项选择题
        List<String> singleChoiceQuestions = HtmlParserUtils.extractSingleChoiceQuestions(doc);
        HashMap<String,  List<String>> singleChoiceQuestionsHashMap = new HashMap<>();
        singleChoiceQuestionsHashMap.put("单项选择题", singleChoiceQuestions);
        // 提取多项选择题
        List<String> multipleChoiceQuestions = HtmlParserUtils.extractMultipleChoiceQuestions(doc);
        HashMap<String,  List<String>> multipleChoiceQuestionsHashMap = new HashMap<>();
        multipleChoiceQuestionsHashMap.put("多项选择题", multipleChoiceQuestions);
        // 提取填空题
        List<String> blankQuestion = HtmlParserUtils.extractBlankQuestions(doc);
        HashMap<String,  List<String>> blankQuestionHashMap = new HashMap<>();
        blankQuestionHashMap.put("填空题", blankQuestion);
        // 不定项选择题
        List<String> notChoiceQuestions = HtmlParserUtils.extractNotChoiceQuestions(doc);
        HashMap<String,  List<String>> notChoiceQuestionsHashMap = new HashMap<>();
        notChoiceQuestionsHashMap.put("不定项", notChoiceQuestions);


        List<String> tableQuestion = HtmlParserUtils.extractTableQuestions(doc);
        HashMap<String,  List<String>> tableQuestionHashMap = new HashMap<>();
        tableQuestionHashMap.put("表格题", tableQuestion);

        // 简答题
        List<String> shortAnswerQuestions = HtmlParserUtils.extractShortAnswerQuestions(doc);
        HashMap<String,  List<String>> shortAnswerQuestionsHashMap = new HashMap<>();
        shortAnswerQuestionsHashMap.put("简答题", shortAnswerQuestions);

        // 综合题
        List<String> comprehensiveQuestions = HtmlParserUtils.extractComprehensiveQuestions(doc);
        HashMap<String,  List<String>> comprehensiveQuestionsHashMap = new HashMap<>();
        comprehensiveQuestionsHashMap.put("综合题", comprehensiveQuestions);


        // 写作题
        List<String> writingQuestions = HtmlParserUtils.extractWriterQuestions(doc);
        HashMap<String,  List<String>> writingQuestionsHashMap = new HashMap<>();
        writingQuestionsHashMap.put("写作题", writingQuestions);

        QuestionCategory questionCategory = new QuestionCategory();

        questionCategory.setJudgmentQuestions(judgmentQuestionsHashMap);
        questionCategory.setSingleChoiceQuestions(singleChoiceQuestionsHashMap);
        questionCategory.setMultipleChoiceQuestions(multipleChoiceQuestionsHashMap);
        questionCategory.setNotChoiceQuestions(notChoiceQuestionsHashMap);
        questionCategory.setBlankQuestion(blankQuestionHashMap);
        questionCategory.setShortAnswerQuestions(shortAnswerQuestionsHashMap);
        questionCategory.setComprehensiveQuestions(comprehensiveQuestionsHashMap);
        questionCategory.setTableQuestions(tableQuestionHashMap);
        questionCategory.setWritingQuestions(writingQuestionsHashMap);

        return success("识别成功" , questionCategory);
    }



    // 图片存储目录
    private static final String UPLOAD_DIR = "src/main/resources/upload";
    /**
     * 上传图片
     */
    @PostMapping(value = "/uploadImage")
    public ApiRest uploadImage(@RequestPart(value = "file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return failure("文件为空");
        }
        try {
            // 获取文件的字节数组
            byte[] bytes = file.getBytes();
            String originalFilename = file.getOriginalFilename();

            // 获取文件的扩展名
            String fileExtension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));

            }
            // 创建存储文件的路径
            Path path = Paths.get(UPLOAD_DIR + File.separator + file.getOriginalFilename());
            // 创建上传文件夹（如果不存在）
            File uploadDir = new File(UPLOAD_DIR);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            // 将文件写入指定路径
            Files.write(path, bytes);
            // 构建完整的文件访问 URL
            String fileUrl = ServletUriComponentsBuilder.fromCurrentContextPath()
                    .path("/upload/")
                    .path(file.getOriginalFilename())
                    .toUriString();

            return success("文件上传成功", fileUrl);
        } catch (IOException e) {
            e.printStackTrace();
            return failure("文件上传失败");
        }
    }
        @Resource
    SubjectsService subjectsService;
    /**
     * 上传图片接口
     */
    @PostMapping(value = "/importImage")
    public ApiRest importWord(@RequestPart(value = "upfile") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return failure("文件为空");
        }
        try {
            byte[] bytes = file.getBytes();
            String originalFilename = file.getOriginalFilename();
            String fileExtension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));

            }
            String fileUrl = ServletUriComponentsBuilder.fromCurrentContextPath()
                    .path("/upload/")
                    .path(file.getOriginalFilename())
                    .toUriString();
            Path path = Paths.get(fileUrl);
            File uploadDir = new File(UPLOAD_DIR);
                if (!uploadDir.exists()) {
                    uploadDir.mkdirs();
                }
                Files.write(path, bytes);
                return success("上传成功");
        } catch (Exception e) {
            e.printStackTrace();
            return failure("上传成功");
        }
    }
    /**
     //     * 导入word
     //     *  @RequestParam("projectId") String projectId,
     //        @RequestParam("subjectId") String subjectId
     //     * @param file
     //     * @return
     //     */
    @ResponseBody
    @RequestMapping(value = "/importWord")
    public ApiRest importWord(@RequestPart(value = "file") MultipartFile file,String subjectId,String outputPath) throws Exception {

        try {

            subjectsService.getSubjectSessionsById(subjectId);
            WordToHtmlConverter.ServerImageHandler serverImageHandler = new WordToHtmlConverter.ServerImageHandler();
            serverImageHandler.subjectSessions = subjectsService.getSubjectSessionsById(subjectId);
            String content = DocxProcessor.processDocxToHtml(file);
            // String content = WordDocumentExtractor.extractFullContent(file);
            // 解析成功后，将文件拷贝到指定目录
          //  String content = docxToHTML.extractOptionsFromDocx(file);
            copyFileToDirectory(file,outputPath);

            return success("解析成功", content);
        } catch (Exception e) {
            e.printStackTrace();
            return failure("解析失败，系统不支持doc文件，请将doc转成docx再导入");
        }

//        LinkedList<String> contentList = new LinkedList<>();
//        XWPFDocument docxDocument = new XWPFDocument(file.getInputStream());
//
//
//        StringBuilder htmlBuilder = new StringBuilder();
  //      String outputFilePath = "C:\\Users\\Administrator\\Desktop\\output.html";
//        htmlBuilder.append("<html><head><title>Converted Document</title></head><body>");
//        List<XWPFParagraph> paragraphs = docxDocument.getParagraphs();
//        for (XWPFParagraph paragraph : paragraphs) {
//            contentList.add(paragraph.getText());
//        }
//
//        for (IBodyElement element : docxDocument.getBodyElements()) {
//            if (element instanceof XWPFParagraph) {
//                htmlBuilder.append(WordToHtmlConverterNew.processParagraph((XWPFParagraph) element,projectId,subjectId));
//            } else if (element instanceof XWPFTable) {
//                htmlBuilder.append(WordToHtmlConverterNew.processTable((XWPFTable) element,projectId,subjectId));
//            }else if(element instanceof XWPFPicture){
//                htmlBuilder.append(WordToHtmlConverterNew.processImage1((XWPFPicture) element,projectId,subjectId));
//            }
//        }
//
//
//        htmlBuilder.append("</body></html>");
//        // 将生成的 HTML 内容存入数据库中
//        contentList.add(htmlBuilder.toString());
//
//
         //将生成的 HTML 内容写入文件
//
//        FileOutputStream fos = new FileOutputStream(outputFilePath);
//        fos.write(content.getBytes());
//        fos.close();



    }

    /**
     * 将 MultipartFile 拷贝到指定目录
     * @param file 待拷贝的 MultipartFile
     * @throws
     */
    private void copyFileToDirectory(MultipartFile file,String outPutPath) throws IOException {
        // 指定目标目录
        String targetDir = outPutPath+ "/backup/";
        File targetDirectory = new File(targetDir);
        // 若目录不存在则创建
        if (!targetDirectory.exists()) {
            targetDirectory.mkdirs();
        }

        // 构建目标文件路径
        String originalFilename = file.getOriginalFilename();
        if (originalFilename != null) {
            File targetFile = new File(targetDirectory, originalFilename);
            // 将文件内容写入目标文件，若文件已存在会覆盖
            file.transferTo(targetFile);
        }
    }







}